import cv2
import pandas as pd
from paddleocr import PaddleOCR, draw_ocr
import os
file="data"


df = pd.read_csv("./"+file+"/1/1.csv", encoding='UTF-8')
tu_folder = "./"+file+"/1/1/"
# 创建 DataFrame，保存结果
result_df = pd.DataFrame(columns=['图片位置', 'text'])
# 初始化 OCR 识别器
ocr = PaddleOCR(use_angle_cls=True, lang='ch')
# 遍历数据框
for index, row in df.iterrows():
    if pd.isna(row['图片位置']):
        continue
    imgname=row['图片位置']
    print(imgname)
    for filename in os.listdir(tu_folder):
        if imgname in filename:
            path = "./"+file +"/1/1/"+filename
            break
    try:
        img = cv2.imread(path)
        # 对图片进行 OCR 文字识别
        result = ocr.ocr(img, cls=False)
        # 保存识别结果到文本变量
        text = ''
        for idx in range(len(result)):
            res = result[idx]
            for line in res:
                text += line[1][0] + '\n'
        # 将识别结果保存到 DataFrame
        result_df.loc[index] = [row['图片位置'], text]
    except Exception as e:
        print(f"Error processing image {imgname}: {e}")
        result_df.loc[index] = [row['图片位置'], ""]
        continue

# 合并原始数据框和识别结果数据框
merged_df = pd.concat([df, result_df['text']], axis=1)

# 将 DataFrame 保存到 CSV 文件中
merged_df.to_csv('./jd_info_with_result.csv', index=False)